/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate.dao;

import hibernate.entity.Conversations;
import hibernate.entity.Entities;
import hibernate.entity.MessageConversations;
import java.util.List;

/**
 *
 * @author Neo
 */
public class MessageDAO extends AbstractDAO {

    /**
     * @param ID an id represent for a receiver to get a subcons list of
     * conversation
     * @return a list of entities
     */
    public List<Entities> readByReceiverID(int ID) {
        query = session.createQuery("select mr from Entities as m  join  m.messageConversationses as mr"
                + " where mr.accountsByReceiverId.accountId = :id "
                + "and mr.receiverStorageStatus = 1");
        query.setParameter("id", ID);
        return query.list();
    }

    /**
     * @param ID an id represent for an assignment 
     * @return List<Entities>
     */
    public List<Entities> readAssignmentByReceiverID(int ID) {
        query = session.createQuery("select mr from Entities as m  join  m.messageConversationses as mr"
                + " where mr.accountsByReceiverId.accountId = :id "
                + "and mr.receiverStorageStatus = 1 and m.entityTypes.name = 'Assignment'");
        query.setParameter("id", ID);
        return query.list();
    }

    /**
     * @param ID an id represent for a sender to get a subcons list of
     * conversation
     * @return List<Entities>
     */
    public List<Entities> readBySenderID(int ID) {
        query = session.createQuery("select mr from Entities as m  join  m.messageConversationses as mr"
                + " where mr.accountsBySenderId.accountId = :id "
                + "and mr.senderStorageStatus = 1");
        query.setParameter("id", ID);
        return query.list();
    }

    /**
     * @param MessageConversations a mc for take it to trash
     * @return int
     */
    public int receiverToTrash(MessageConversations mc) {
        try {
            tx = session.beginTransaction();
            mc.setReceiverStorageStatus(0);
            mc = (MessageConversations) session.merge(mc);
            session.update(mc);
            tx.commit();
            return 1;
        } catch (Exception e) {
            tx.rollback();
            return 0;
        }

    }

    /**
     * @param Conversations a conversation entered to get all of messages in the
     * conversation
     * @return List of messages in the conversation
     */
    public List<MessageConversations> readByConversation(Conversations con) {
        query = session.createQuery("from MessageConversations mc where mc.conversations = :con");
        query.setParameter("con", con);
        return query.list();
    }
}
